import sys
from io import BytesIO
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
from Ui_AES import Ui_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow,QPushButton, QPlainTextEdit,QLabel,QMessageBox
class myclass():
    def __init__(self) -> None:
        pass
class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self):
        super(MainWindow,self).__init__()
        self.setupUi(self)
        #在此输入connect链接
        self.show()
        self.k = 'cqyisthebesttman'.encode('utf-8')  # 密钥
        self.iv = b'1234567890asdfgh'  # 偏移量
        self.mode = AES.MODE_CBC  # 模式 
        self.pushButton_jiami.clicked.connect(self.jiami)
        self.pushButton_jiemi.clicked.connect(self.jiemi)

    def cryp_str(self,value):
        value = value.encode('utf-8') # 对数据进行utf-8编码
        cryptor = AES.new(self.k, self.mode, self.iv) # 创建一个新的AES实例
        length = 16
        count = len(value)
         # 如果数据长度小于密钥长度
        if count < length:
           add = (length - count)
           # \0 backspace
           text = value + ('\0' * add).encode('utf-8')
        elif count > length:
           add = (length - (count % length))
           text = value + ('\0' * add).encode('utf-8')
        ciphertext = cryptor.encrypt(text) # 加密字符串
        ciphertext_hex = b2a_hex(ciphertext) # 字符串转十六进制数据
        ciphertext_hex_de = ciphertext_hex.decode()
        return ciphertext_hex_de   
    def decry_str(self,value):
        cryptor = AES.new(self.k, self.mode, self.iv) # 创建一个AES实例
        value_hex = a2b_hex(value) # 将十六进制数据转换为字符串
        plain_text = cryptor.decrypt(value_hex) # 对字符串进行解密
        return bytes.decode(plain_text).rstrip('\0')

    def jiami(self):
        self.textEdit_miwen.clear()
        self.yuanwen=self.textEdit_yuanwen.toPlainText()
        self.textEdit_miwen.insertPlainText(self.cryp_str(self.yuanwen))


    def jiemi(self):  
        self.miwen=self.textEdit_miwen.toPlainText()
        s=self.decry_str(self.miwen)
        print(s)
        self.textEdit_yuanwen.clear()
        self.textEdit_yuanwen.insertPlainText(s)
if __name__ == "__main__":  # 主函数执行
    app = QApplication(sys.argv)
    globFont = QtGui.QFont()
    globFont.setFamily('Microsoft YaHei')
    globFont.setPointSize(10)
    app.setFont(globFont)
    MainUI = MainWindow()  # 将主界面定义为欢迎界面，程序运行至此处开始调用MainWindow()类
    sys.exit(app.exec_())  # 程序执行完毕后关闭
